'use strict';

import path from 'path'
import axios from 'axios'
import semver from 'semver'
import log from '@breeze-cli-dev/log'
function getNpmInfo(npmName, registry) {
  if (!npmName) return null
  const registryUrl = registry || 'https://registry.npmjs.org'
  const npmInfoUrl = path.join(registryUrl, npmName)
  // console.log('请求npm地址为:', npmInfoUrl)
  return axios.get(npmInfoUrl).then(res => {
    if (res.status === 200) {
      if (res.data && res.data.versions) {
        return Object.keys(res.data.versions)
      }
    } else {
      return []
    }
  }).catch(error => {
    log.warn('npm接口出错，未找到包的地址')
    return []
  })
}
// 获取当前版本的最新版本
function getNpmSemverVersion(baseVersion, npmName, registry) {
  // const registryAll = await getNpmInfo(npmName, registry)
  return getNpmInfo(npmName, registry).then(res => {
    const registryAll = res
    if (registryAll && registryAll.length > 0) {
      const newsSemverRegistry = registryAll.filter(item => semver.satisfies(item, `>${baseVersion}`)).sort((a, b) => semver.gt(b, a))
      if (newsSemverRegistry.length > 0) {
        return newsSemverRegistry[0]
      }
    }
    return null
  })
}
function getDefaultRegistry(isOriginal = false) {
  return isOriginal ? 'https://registry.npmjs.org' : 'https://registry.npmmirror.com';
}
// 获取当前最新版本
async function getNpmLatestVersion(npmName, registry) {
  const versions = await getNpmInfo(npmName, registry)
  if (versions && versions.length > 0) {
    return versions.sort((a, b) => semver.gt(b, a))[versions.length - 1];
  }
  return null
}
export {
  getNpmInfo,
  getNpmSemverVersion,
  getDefaultRegistry,
  getNpmLatestVersion
}